/*
 Run the background estimation. 'background.h' should be included.
*/
#include <iostream>
#include <ctime>
#include <io.h>    
#include <direct.h>

#include "background.h"//background estimation

#include "lodepng.h"//for loading the png image

using namespace std;

void getFiles( string, vector<string>& );//go through a file folder

int main(){

	unsigned width, height;
	int k = 0;
	vector<string>  files;    

	char * filePath = "C:\\Users\\Lm\\Documents\\MATLAB\\Background estimation\\130507AF9_p0040"; //folder path
    getFiles(filePath, files);  
   
    for( k=0; k<files.size(); k++) //for all the files in the folder
	{
		
		if( files[k].find("w01.png")==string::npos)continue; //only read png files
		
		unsigned short* out = NULL;
		unsigned char * input = NULL;

		//read the image: png format, 8bit, in rows from top to bottom
		
		//char* imageName = "C:\\Users\\Lm\\Documents\\MATLAB\\Background estimation\\130507AF9_p0040\\130507AF9_p0040_t00100_z001_w01.png";
		//unsigned int error = lodepng_decode_file(&input, &width, &height, imageName,LCT_GREY,8);
	
		unsigned int error = lodepng_decode_file(&input, &width, &height, files[k].c_str(),LCT_GREY,8);
		cout<<"Load image: "<<files[k]<<endl;

		char outName[100];
		files[k].pop_back();
		files[k].pop_back();
		files[k].pop_back();
		files[k].pop_back();
		strcpy(outName,files[k].c_str());
		strcat(outName,".txt"); //write the output as a txt file with the same file name

		int	sizeX = width;
		int	sizeY = height;
	
		clock_t start,end;
		start = clock();
		backGroundEsimation(input,sizeX,sizeY,&out); //background estimation
		end = clock();
		cout<<"Running time is "<<(double)(end - start) * 1000.0 / CLOCKS_PER_SEC << " ms!" << endl;
	
		FILE *pFile;
		pFile = fopen(outName,"w");
		for (int i = 0;i < sizeY;i++)
		{
			for (int j = 0;j<sizeX;j++)
			{
				fprintf(pFile,"%d ",out[i*sizeX+j]);
			}
			fprintf(pFile,"\n");
		}
		fclose(pFile);
		cout<<"Output file created."<<endl<<endl;
		free(out);
		free(input);
	}
	system("pause");
	return 0;
}


void getFiles( string path, vector<string>& files ) {  
  
    long   hFile   =   0;    
 
    struct _finddata_t fileinfo;    
  
    string p;  
  
    if   ((hFile   =   _findfirst(p.assign(path).append("/*").c_str(),&fileinfo))   !=   -1)  {    
  
        do  {     
            if   ((fileinfo.attrib   &   _A_SUBDIR)) {    
                if   (strcmp(fileinfo.name,".")   !=   0   &&   strcmp(fileinfo.name,"..")   !=   0)    
                    getFiles(   p.assign(path).append("/").append(fileinfo.name), files   );    
            }  else  {    
                files.push_back(   p.assign(path).append("/").append(fileinfo.name)  );  
            }    
        }   while   (_findnext(   hFile,   &fileinfo   )   ==   0);    
  
        _findclose(hFile);    
    }  
}  